package com.zhang.framelib.util.page;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Field;

/**
 * 反射工具.
 */
public class ReflectHelper {
    
    private static Logger logger = LoggerFactory.getLogger(ReflectHelper.class);
    /**
     * 获取obj对象fieldName的Field.
     * 
     */
    
    public static Field getFieldByFieldName(Object obj, String fieldName) {

        /*
         * for (Class<?> superClass = obj.getClass(); superClass !=
         * Object.class; superClass = superClass .getSuperclass()) { try {
         * return superClass.getDeclaredField(fieldName); } catch
         * (NoSuchFieldException ne) { logger.error("找不到属性", ne); } }
         */

        Class<?> superClass = obj.getClass();
        while (true) {
            if (superClass != Object.class) {
                try {
                    return superClass.getDeclaredField(fieldName);
                } catch (Exception exception) {
                    superClass = superClass.getSuperclass();
                }
            } else {
                logger.error("属性:{}找不到", fieldName);
                break;
            }
        }
        return null;
    }

    /**
     * 获取obj对象fieldName的属性值.
     * @param obj 对象.
     * @param fieldName 属性名称.
     * @return 返回object对象 
     * @throws SecurityException 安全异常.
     * @throws NoSuchFieldException 文件找不到异常.
     * @throws IllegalArgumentException 非法参数异常.
     * @throws IllegalAccessException 非法访问异常.
     */
    public static Object getValueByFieldName(Object obj, String fieldName)
            throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException {
        Field field = getFieldByFieldName(obj, fieldName);
        Object value = null;
        if (field != null) {
            if (field.isAccessible()) {
                value = field.get(obj);
            } else {
                field.setAccessible(true);
                value = field.get(obj);
                field.setAccessible(false);
            }
        }
        return value;
    }

    /**
     * 设置obj对象fieldName的属性值
     * 
     * @param obj 对象.
     * @param fieldName 属性名称.
     * @param value 对象.
     * @throws SecurityException 安全异常.
     * @throws NoSuchFieldException 文件找不到异常.
     * @throws IllegalArgumentException 非法参数异常.
     * @throws IllegalAccessException 非法访问异常.
     */
    public static void setValueByFieldName(Object obj, String fieldName, Object value)
            throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException {
        Field field = obj.getClass().getDeclaredField(fieldName);
        if (field.isAccessible()) {
            field.set(obj, value);
        } else {
            field.setAccessible(true);
            field.set(obj, value);
            field.setAccessible(false);
        }
    }
}
